package com.difsonapps.android.marker.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.difsonapps.android.marker.AppConstant;
import com.difsonapps.android.marker.CustomRequest;
import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.R.layout;
import com.difsonapps.android.marker.adapters.ProfilePagerAdapter;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.Friend;
import com.difsonapps.android.marker.beans.User;
import com.difsonapps.android.marker.util.MarkerUtil;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass. Activities that
 * contain this fragment must implement the
 * {@link ProfileFragment.OnFragmentInteractionListener} interface to handle
 * interaction events. Use the {@link ProfileFragment#newInstance} factory
 * method to create an instance of this fragment.
 * 
 */
public class ProfileFragment extends Fragment {
	// TODO: Rename parameter arguments, choose names that match
	// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
	NetworkImageView profileImageView;
	TextView usernameTextView;
	TextView userfunctionTextView;
	TextView firstnameTextView;
	TextView lastnameTextView;
	TextView middlenameTextView;
	TextView occupationTextView;
	TextView aboutmeTextView;
	//View contentScrollView;
	
	Button buttonDeleteFriend;
	Button buttonAcceptDemand;
	Button buttonDeclineDemand;
	Button buttonAddFriend;
	TextView demandSentTextView;
	
	ImageLoader imageLoader = AppController.getInstance().getImageLoader();
	
	User user;

	/**
	 * Use this factory method to create a new instance of this fragment using
	 * the provided parameters.
	 * 
	 * @param param1
	 *            Parameter 1.
	 * @param param2
	 *            Parameter 2.
	 * @return A new instance of fragment ProfileFragment.
	 */
	// TODO: Rename and change types and number of parameters
	public static ProfileFragment newInstance(User user) {
		ProfileFragment fragment = new ProfileFragment();
		Bundle args = new Bundle();
		args.putParcelable("user", user);
		fragment.setArguments(args);
		return fragment;
	}

	public ProfileFragment() {
		// Required empty public constructor
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getArguments() != null) {
			user = getArguments().getParcelable("user");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
		//contentScrollView = rootView.findViewById(R.id.contentScrollView);
		profileImageView = (NetworkImageView)rootView.findViewById(R.id.profileImageView);
		usernameTextView = (TextView)rootView.findViewById(R.id.usernameTextView);
		userfunctionTextView = (TextView)rootView.findViewById(R.id.userfunctionTextView);
		firstnameTextView = (TextView)rootView.findViewById(R.id.firstnameTextView);
		lastnameTextView = (TextView)rootView.findViewById(R.id.lastnameTextView);
		middlenameTextView = (TextView)rootView.findViewById(R.id.middlenameTextView);
		occupationTextView = (TextView)rootView.findViewById(R.id.occupationTextView);
		aboutmeTextView = (TextView)rootView.findViewById(R.id.aboutmeTextView);
		if(user==null) user = AppConstant.userConnected;
		if(user!=null){
			usernameTextView.setText(user.getName());
			//userfunctionTextView.setText(user.get);
			firstnameTextView.setText(user.getFirstname());
			lastnameTextView.setText(user.getLastname());
			middlenameTextView.setText(user.getMiddlename());
			occupationTextView.setText(user.getOccupation());
			aboutmeTextView.setText(user.getAboutMe());
			profileImageView.setImageUrl(user.getPictureUrl(), imageLoader);
		}
		
		buttonDeleteFriend = (Button)rootView.findViewById(R.id.delete_friend_button);
		buttonAcceptDemand = (Button)rootView.findViewById(R.id.accept_demand_button);
		buttonDeclineDemand = (Button)rootView.findViewById(R.id.decline_demand_button);
		buttonAddFriend = (Button)rootView.findViewById(R.id.add_to_friends_button);
		demandSentTextView = (TextView)rootView.findViewById(R.id.demand_sent_text);
		
		buttonDeleteFriend.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				btnDeleteFriendClick(v);
			}
		});
		buttonAcceptDemand.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				btnAcceptDemandClick(v);
			}
		});
		buttonDeclineDemand.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				btnDeclineDemandClick(v);
			}
		});
		buttonAddFriend.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				btnAddFriendClick(v);
			}
		});
		//TODO the bar to manage the user
		loadFriendStatus();
		return rootView;
	}
	

	public void btnAddFriendClick(View v){
		loadAddFriend();
	}
	public void btnDeleteFriendClick(View v){
		loadDeleteFriend();
	}
	public void btnAcceptDemandClick(View v){
		loadAcceptDemand();
	}
	public void btnDeclineDemandClick(View v){
		loadDeclineDemand();
	}

	
	Friend friend1 = null;
	Friend friend2 = null;
	
	private void loadFriendStatus(){
		if(AppConstant.userConnected==null || user==null || AppConstant.userConnected.getId()==user.getId()) return;

    	Map<String, String> params = new HashMap<String, String>();
        params.put("id", ""+user.getId());
        String url = MarkerUtil.buildUrl(AppConstant.friendStatusUrl, params);
        CustomRequest jsObjRequest = new CustomRequest(
				Method.GET, 
				url, 
				null,
				new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                    	parseJsonFriendStatus(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	//hideProgress();
                    	toast("Error: " + error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}	
	
	private void loadAcceptDemand(){
		if(friend2==null) return;
    	Map<String, String> params = new HashMap<String, String>();
        params.put("id", ""+friend2.getId());
        String url = MarkerUtil.buildUrl(AppConstant.acceptDemandUrl, params);
        CustomRequest jsObjRequest = new CustomRequest(
				Method.GET, 
				url, 
				null,
				new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                    	parseJsonFriendStatus(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	//hideProgress();
                    	toast("Error: " + error.getMessage());
                    }
                }
        );
       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	private void loadDeclineDemand(){
		if(friend2==null) return;
    	Map<String, String> params = new HashMap<String, String>();
        params.put("id", ""+friend2.getId());
        String url = MarkerUtil.buildUrl(AppConstant.declineDemandUrl, params);
        CustomRequest jsObjRequest = new CustomRequest(
				Method.GET, 
				url, 
				null,
				new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                    	parseJsonFriendStatus(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	//hideProgress();
                    	toast("Error: " + error.getMessage());
                    }
                }
        );
       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}

	private void loadDeleteFriend(){
		if(friend1==null) return;
    	Map<String, String> params = new HashMap<String, String>();
        params.put("id", ""+friend1.getId());
        String url = MarkerUtil.buildUrl(AppConstant.deleteFriendUrl, params);
        toast("Delete url : "+url);
        CustomRequest jsObjRequest = new CustomRequest(
				Method.GET, 
				url, 
				null,
				new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                    	parseJsonFriendStatus(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	//hideProgress();
                    	toast("Error: " + error.getMessage());
                    }
                }
        );
       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	private void loadAddFriend(){
		if(friend1!=null) return;
    	Map<String, String> params = new HashMap<String, String>();
        params.put("id", ""+user.getId());
        String url = MarkerUtil.buildUrl(AppConstant.addFriendUrl, params);
        toast("Add url : "+url);
        CustomRequest jsObjRequest = new CustomRequest(
				Method.GET, 
				url, 
				null,
				new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                    	parseJsonFriendStatus(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	//hideProgress();
                    	toast("Error: " + error.getMessage());
                    }
                }
        );
       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	
	private void parseJsonFriendStatus(JSONObject response) {
        try {
        	toast(response.toString());
        	
        	
            if(response.has("success")){
            	if(response.has("friend1")) friend1 = Friend.parseFromJsonObject(response.getJSONObject("friend1"));
            	else friend1 = null;
            	if(response.has("friend2")) friend2 = Friend.parseFromJsonObject(response.getJSONObject("friend2"));
            	else friend2 = null;
            	hideAllStatus();
            	if(friend1!=null && friend1.isConfirmed()){
            		buttonDeleteFriend.setVisibility(View.VISIBLE);
            	}else if(friend1!=null){//TODOD Show demand sent
            		demandSentTextView.setVisibility(View.VISIBLE);
            	}else if(friend2!=null && !friend2.isDeclined()){
            		buttonAcceptDemand.setVisibility(View.VISIBLE);
            		buttonDeclineDemand.setVisibility(View.VISIBLE);
            	}else if(friend2!=null && friend2.isDeclined()){
            		buttonAddFriend.setVisibility(View.VISIBLE);
	        	}else if(friend1==null && friend2==null){
            		buttonAddFriend.setVisibility(View.VISIBLE);
            	}
            	
            }else if(response.has("error")){
            	String error = response.getString("error");
            	//TODO Show the error message in a textView and make it visible
            	toast(error);
            	//hideProgress();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("Profile fragment", e.getMessage());
        }
    }
	
	public void hideAllStatus(){
		buttonAcceptDemand.setVisibility(View.GONE);
		buttonDeclineDemand.setVisibility(View.GONE);
		buttonDeleteFriend.setVisibility(View.GONE);
		buttonAddFriend.setVisibility(View.GONE);
		demandSentTextView.setVisibility(View.GONE);
	}

    private void toast(String text){
		Toast.makeText(this.getActivity(), text, Toast.LENGTH_SHORT).show();
	}

}
